package aos.socket;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.Queue;

import aos.entity.Message;
import aos.exception.AosException;
import aos.log.LogUtils;

public class SocketHandler implements Runnable {
	private Socket socket;
	private ObjectOutputStream os;
	private ObjectInputStream is;
	private Queue<Message> messageQueue;

	public SocketHandler(Socket socket, Queue<Message> messageQueue) {
		this.socket = socket;
		this.messageQueue = messageQueue;
		try {
			os = new ObjectOutputStream(this.socket.getOutputStream());
			is = new ObjectInputStream(this.socket.getInputStream());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void run() {
		// System.out.println("socket start listening");
		Message msg = null;
		while (true) {
			try {
				msg = (Message) is.readObject();
			} catch (ClassNotFoundException e) {
				LogUtils.errorLog(e.getMessage());
				break;
			} catch (IOException e) {
				LogUtils.errorLog(e.getMessage());
				break;
			}
			LogUtils.runLog("Receiving message...  " + msg.toString());
			synchronized (messageQueue) {
				messageQueue.add(msg);
				LogUtils.debugLog("message enqueue success: " + msg.toString());
				messageQueue.notify();
			}
		}
	}

	public void sendMessage(Message msg) throws AosException {
		try {
			os.writeObject(msg);
			os.flush();
		} catch (IOException e) {
			LogUtils.errorLog("writeObject failed, to "
					+ socket.getInetAddress().getHostAddress());
			LogUtils.errorLog(e.getMessage());
			throw new AosException(e.getMessage(), e);
		}
		LogUtils.runLog("Sending message...  " + msg.toString());
	}
}